# ！/usr/bin/evn python
# coding=utf-8
from . import *

sys.path.append(os.getcwd())


class PushUtils:
    @staticmethod
    def get_push():
        push = getattr(g, 'push', None)
        if push is None:
            APP_KEY = '523a9dc61c52c9dc861d7c32'
            MASTER_SECRET = 'f5180a2011d291dd831ebb6e'
            push = jpush.JPush(APP_KEY, MASTER_SECRET).create_push()
            push.options = {"apns_production": True, 'time_to_live': (86400 * 7)}
            push.audience = jpush.all_
            g.push = push
        return push

    @staticmethod
    def set_msg(alert='', badge=0, alias=None):
        _push = PushUtils.get_push()
        ios_msg = jpush.ios(
            alert=alert, badge=badge,
            extras={}, sound_disable=True if not alert else False,
            sound='default')
        android_msg = jpush.android(
            alert=alert, extras={'badge': badge})
        _push.audience = jpush.audience(jpush.alias(alias))
        _push.notification = jpush.notification(
            ios=ios_msg, android=android_msg)
        _push.platform = jpush.all_
        PushUtils.execute()

    @staticmethod
    def execute():
        try:
            PushUtils.get_push().send()
        except common.Unauthorized:
            raise common.Unauthorized("Unauthorized")
        except common.APIConnectionException:
            raise common.APIConnectionException("conn error")
        except common.JPushFailure:
            print("JPushFailure")
        except:
            print("Exception")
